import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:laos_mall/app_route.dart';
import 'package:laos_mall/common/base/base_controller.dart';
import 'package:laos_mall/common/style/extension_util.dart';
import 'package:laos_mall/common/utils/http_util.dart';
import 'package:laos_mall/common/widght/toast/showtoast.dart';
import 'package:laos_mall/models/config/area_code_model.dart';
import 'package:laos_mall/models/home/home_model.dart';
import 'package:laos_mall/pages/main/catergory/sku/view.dart';
import 'package:laos_mall/pages/main/config.dart';
import 'package:laos_mall/pages/main/home/widgets/language_dialog.dart';
import 'package:laos_mall/user_data.dart';

class HomeLogic extends BaseController with GetSingleTickerProviderStateMixin {
  var images = <Products>[];
  var categorys = [];
  late TabController tabCtl;
  var tabScroll = true.obs;
  var pageCtrls = [];
  var swiperCtrls = [];
  late ScrollController scrollController;
  AreaCodeModel? areaCode;

  @override
  void onInit() {
    scrollController = ScrollController();
    super.onInit();
    // pageCtrls = categorys.map((e) => PageController()).toList();
    // swiperCtrls = categorys.map((e) => PageController()).toList();
  }

  @override
  initConfig() async {
    await Future.wait([homeData(), language(), getAreaCode()]);
    update();
  }

  Future<void> homeData() async {
    var res = await HttpUtil.restApi.homeData({});
    categorys = res.data?.category ?? [];
    images = res.data?.list ?? [];
    tabCtl = TabController(length: categorys.length, vsync: this);
  }

  Future<void> language() async {
    var res = await HttpUtil.restApi.languageList({});
    res.data?.items?.forEach((e) {
      var item = Config.languages.firstWhereOrNull(
          (element) => element.value.toString().contains(e.locale_code));
      item?.defaultValue = e.locale_code;
    });
  }

  Future<void> getAreaCode() async {
    var res = await HttpUtil.restApi.areaCode({});
    areaCode = res.data;
  }

  ///处理数据源
  getProductInCategory(String category) {
    return images
        .where((element) => element.category == category)
        .toList()
        .reversed
        .toList();
  }

  jumpLanguage() {
    Get.bottomSheet(const LanguageDialog(), isScrollControlled: true);
  }

  jumpLogin(Products product) {
    UserData().loginJudge(callback: ()async {
      if(product.sku_id != 0) {
        Get.bottomSheet(SkuPage(skuId: product.sku_id,productId: product.product_id,));
      }else{
        ///todo:  is_quick 首页未提供
        var param = {"id":product.product_id,"number":1,"sku_id":0,"is_quick":0};
        var res = await HttpUtil.restApi.addToCart(param);
        if(res.code == 0){
          showToast("hint_add_cart_success".tr,type: ToastType.success);
        }else{
          showToast("hint_add_cart_fail".tr,type: ToastType.error);
        }
      }
    });
  }
}
